package com.gxa.controller.statisticalControl;

import com.gxa.exception.GlobalException;
import com.gxa.pojo.entity.tjgl.ChannelPieChart;
import com.gxa.pojo.entity.tjgl.Pagination;
import com.gxa.pojo.entity.tjgl.VisitorsOverview;
import com.gxa.pojo.entity.tjgl.VisitorsTrend;
import com.gxa.pojo.entity.tjgl.util.DateInfo;
import com.gxa.service.statistical.VisitorsService;
import com.gxa.utils.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * query controller
 *
 * @author IKE <hp1041735092@outlook.jp>
 * @date 23/2/2024
 */

@RequestMapping("/statistic/visitors")
@RestController
public class VisitorsController {
    @Resource
    private VisitorsService visitorsService;

    /**
     * reception staff overview
     */
    @GetMapping("/getRecepOverview")
    public CustomResult<VisitorsOverview> queryOverview() {
        return ResultUtils.buildSuccessResponse(visitorsService.queryOverview());
    }

    /**
     * create a Pagination class to receive the data from db >>> 1.total number of data items   2.data list for each row
     * reception staff summary
     * with pagehelper
     * return example:
     * {
     * "code":200,
     * "msg":"success,
     * "data":{
     * "count":2,
     * "rows":[{
     * "id":1,
     * "name":"ike",
     * "age":20,
     * ...
     * }]}}
//     */
//    @GetMapping("/getRecepSummary")
//    public CustomResult<Pagination> queryStaffSummary(
//            @RequestParam(defaultValue = "1") int pageNum,
//            @RequestParam(defaultValue = "5") int pageSize,
//            @RequestParam(defaultValue = "1970-01-01 00:00:00") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")String beginDate,
//            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endDate,
//            @RequestParam(required = false) String username
//    ) {
//
//        if (pageNum <= 0 || pageSize <= 0) {
//            throw new GlobalException(MessageCode.PARAMETER_ERROR);
//        }
//
//        Pagination paginatedData = visitorsService.queryStaffSummary(pageNum, pageSize,beginDate,endDate,username);
//
//        return ResultUtils.buildSuccessResponse(paginatedData);
//    }

    @GetMapping("/getRecepSummary")
    public Result queryStaffSummary(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize,
            @RequestParam(defaultValue = "1970-01-01 00:00:00") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")String beginDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endDate,
            @RequestParam(required = false) String username
    ) {

        if (pageNum <= 0 || pageSize <= 0) {
            throw new GlobalException(MessageCode.PARAMETER_ERROR);
        }

        QueryResult paginatedData = visitorsService.queryStaffSummary(pageNum, pageSize,beginDate,endDate,username);

        return ResultUtils.buildSuccess(paginatedData.getData(),paginatedData.getCount());
    }

    @GetMapping("/getRecepPie")
    public CustomResult<ChannelPieChart> queryPieChartReception(@RequestParam(defaultValue = "") String date){
         /*
            yearMonth is not null and format is correct => return
            yearMonth is null and format is correct => return
            yearMonth format is not correct => throw exception(or use default value?)
          */

        DateInfo parsedDate = DateInfo.fromString(date);

        ChannelPieChart channelPieChart = visitorsService.queryPieChartReception(parsedDate);

//        if (StringUtils.hasLength(yearMonth)){
//            try{
//                LocalDate parse = LocalDate.parse(yearMonth);
//                channelPieChart = visitorsService.queryPieChartReception(parse);
//            }catch (Exception e){
//                LocalDate now = LocalDate.now();
//                channelPieChart = visitorsService.queryPieChartReception(now);
//            }
//        }else {
//            LocalDate now = LocalDate.now();
//            channelPieChart = visitorsService.queryPieChartReception(now);
//        }

        return ResultUtils.buildSuccessResponse(channelPieChart);
    }

    @GetMapping("/getRecepTrend")
    public CustomResult<List<VisitorsTrend>> queryReceptionTrend(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String beginDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate
    ){
        /*
            beginDate default = a month ago
            endDate default = now
            Date format invalid => throw exception (or use default value?)
            @return List<Date,Integer> => List<VisitorsTrend>  Per day data
         */
        LocalDate recentMonth = LocalDate.now();    //current time
        LocalDate pastMonths = recentMonth.minusMonths(1); //a month ago
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate parsedBeginDate = customParseDate(beginDate,pastMonths,formatter);
        //parse endDate str to LocalDate if valid;while method caught exception:use default value(now)
        LocalDate parsedEndDate = customParseDate(endDate,recentMonth,formatter);

        /*determine date order*/
        LocalDate checkedBeginDate = parsedBeginDate;
        LocalDate checkedEndDate = parsedEndDate;
        if (parsedEndDate.isBefore(parsedBeginDate)){
            checkedBeginDate = parsedEndDate;
            checkedEndDate = recentMonth;
        }

        List<VisitorsTrend> recepTrend = visitorsService.queryTrendReception(checkedBeginDate,checkedEndDate);


//        List<VisitorsTrend> recepTrend;
//        LocalDate beginDateParse;
//        LocalDate endDateParse;
//        if (!beginDate.equals("1970-01-01")){       //customized beginDate
//            if (StringUtils.hasLength(endDate)){    //customized endDate
//                try{
//                    beginDateParse = LocalDate.parse(beginDate);  //format beginDate
//                    endDateParse = LocalDate.parse(endDate);      //format endDate
//                    recepTrend = visitorsService.queryTrendReception(beginDateParse,endDateParse);
//                }catch (Exception e){
//                    beginDateParse = LocalDate.parse("1970-01-01");
//                    endDateParse = LocalDate.now();
//                    recepTrend = visitorsService.queryTrendReception(beginDateParse,endDateParse);
//                }
//            }else {     //not customized endDate
//                endDateParse = LocalDate.now();
//                recepTrend = visitorsService.queryTrendReception(beginDate,endDateParse);
//            }
//        }else {     //beginDate = 1970-01-01
//            if (StringUtils.hasLength(endDate)){    //customized endDate
//                //...
//            }else {
//                endDateParse = LocalDate.now();     //endDate = now
//                recepTrend = visitorsService.queryTrendReception(beginDate,endDateParse);
//            }
//            //...
//        }
//        //...
        return ResultUtils.buildSuccessResponse(recepTrend);
    }

    private LocalDate customParseDate(String dateStr,LocalDate defaultDate, DateTimeFormatter formatter) {
        /*
            format invalid => return parsed  value
            format valid   => return default value
         */
        try {
            return LocalDate.parse(dateStr, formatter);
        }catch (Exception e){
            return defaultDate;
        }
    }


    @GetMapping("/getVisitorOverview")
    public CustomResult<VisitorsOverview> queryVisitorOverview(){
        return ResultUtils.buildSuccessResponse(visitorsService.queryVisitorOverview());
    }

    /**
     * @return List<Date,Integer> =>List<VisitorsTrend>
     */
    @GetMapping("/getVisitTrend")
    public CustomResult<List<VisitorsTrend>> queryVisitTrend(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String beginDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") String endDate
    ) {
        /*
            if endDate is null => endDate = LocalDate.now()
            if beginDate is null => beginDate = endDate.minusMonths(1)
         */
        LocalDate currentDate = LocalDate.now();    //current time(endDate default)
        LocalDate lmDate = currentDate.minusMonths(1); //last month date

        //date format method
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parsedBeginDate = customParseDate(beginDate,lmDate,formatter);
        //parse endDate str to LocalDate if valid;while method caught exception:use default value(now)
        LocalDate parsedEndDate = customParseDate(endDate,currentDate,formatter);

        /*determine date order*/
        LocalDate checkedBeginDate = parsedBeginDate;
        LocalDate checkedEndDate = parsedEndDate;
        if (parsedEndDate.isBefore(parsedBeginDate)){
            checkedBeginDate = parsedEndDate;
            checkedEndDate = currentDate;
        }

        List<VisitorsTrend> recepTrend = visitorsService.queryVisitTrend(checkedBeginDate,checkedEndDate);

        return ResultUtils.buildSuccessResponse(recepTrend);
    }



}
